package com.future.message.configuration.Filter;

import com.future.message.Service.UserService;
import com.future.message.Utils.ResponseResult;
import com.future.message.configuration.Security.TokenManager;
import com.future.message.pojo.SecurityUser;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:登录验证过滤器
 * @projectName:message
 * @see:com.future.message.configuration.Filter
 * @author:Xuyujie
 * @createTime:2021/12/6 8:47
 * @version:1.0
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private TokenManager tokenManager;
    private UserService userService;
    private AuthenticationManager authenticationManager;

    public TokenLoginFilter(TokenManager tokenManager, UserService userService, AuthenticationManager authenticationManager) {
        this.tokenManager = tokenManager;
        this.userService = userService;
        this.authenticationManager = authenticationManager;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/user/login"));
    }

    /**
     * 获取表单提交的内容
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        String username = request.getParameter("username");

        String password = request.getParameter("password");
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username,password,new ArrayList<>()));

    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        SecurityContextHolder.getContext().setAuthentication(authResult);
        //得到认证之后的用户信息
        SecurityUser securityUser = (SecurityUser) authResult.getPrincipal();
        //根据用户名生成Token
        Map<String, String> map = new HashMap<>();
        map.put("username",securityUser.getCurrentUserInfo().getAccount());
        map.put("nikeName",securityUser.getCurrentUserInfo().getNickName());
        map.put("grade",securityUser.getCurrentUserInfo().getGrade().toString());
        map.put("department",securityUser.getCurrentUserInfo().getDepartment());
        map.put("userId",securityUser.getCurrentUserInfo().getUserId().toString());
        String toekn = tokenManager.createToken(map);
        HashMap<String, String> result = new HashMap<>();
        result.put("token",toekn);
        logger.info(securityUser.getUsername()+":登录成功   时间："+ LocalDateTime.now());
        ResponseResult.out(response,ResponseResult.success("登录成功！",result));
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        ResponseResult.out(response,ResponseResult.error("账号或密码有误！"));
    }
}
